<template>
    <component :is="components[type]"
               v-model="data"
               v-bind="{...$attrs,type}"
               v-on="$listeners"
               :style="{width}"></component>
</template>

<script>
import {Cascader, ColorPicker, DatePicker, Input, InputNumber, Rate, Slider, Switch, TimePicker} from 'element-ui'

export default {
    name: 'FormItemFactory',
    props: {
        // 表单项的类型，指定对应渲染的组件
        type: {
            type: String,
            default: () => 'input'
        },
        // 可传入自定义组件
        component: {
            type: Function
        },
        value: {
            type: [String, Array, Object, Boolean, Number, Date]
        },
        width: {
            type: String,
            default: '100%'
        }
    },
    data() {
        return {
            components: {
                input: Input,
                number: InputNumber,
                textarea: Input,
                cascader: Cascader,
                switch: Switch,
                slider: Slider,
                time: TimePicker,
                date: DatePicker,
                daterange: DatePicker,
                week: DatePicker,
                month: DatePicker,
                year: DatePicker,
                dates: DatePicker,
                datetime: DatePicker,
                rate: Rate, // 评分
                color: ColorPicker, // 颜色选择器
                upload: () => import('@/components/Form/FormItemFactory/components/uploadFile'),
                tree: () => import('@/components/Form/FormItemFactory/components/treeSelect'),
                select: () => import('@/components/Form/FormItemFactory/components/select'),
                checkbox: () => import('@/components/Form/FormItemFactory/components/checkbox'),
                radio: () => import('@/components/Form/FormItemFactory/components/radioGroup')
            },
            data: undefined
        }
    },
    mounted() {
        this.data = this.value
        if (this.component !== undefined) {
            this.components[this.type] = this.component
        }
    },
    watch: {
        data: {
            handler(newV) {
                if (!newV) return
                this.$emit('input', newV)
            }
        },

        value: {
            handler(newV) {
                this.data = newV
            }
        }
    }
}
</script>

<style lang="scss" scoped>
</style>
